package cn.krui.helper.tools;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author zc
 * Map工具类
 */
public class MapUtils { 
	
	public static String getString(Map<String, Object> map, String key) {
		return getString(map, key, null);
	}

	public static String getString(Map<String, Object> map, String key, String defaultVal) {
		final Object o = map.get(key);
		try {
			if (o == null && defaultVal != null) {
				return defaultVal;
			} else if (o == null && defaultVal == null) {
				return null;
			} else {
				return String.valueOf(o);
			}
		} catch (ClassCastException e) {
			return defaultVal;
		}
	}

	public static int getInt(Map<String, Object> map, String key, int defaultVal) {
		final Object o = map.get(key);
		try {
			if ((o == null || o.equals("")) && defaultVal != 0) {
				return defaultVal;
			} else if ((o == null || o.equals("")) && defaultVal == 0) {
				return 0;
			} else {
				return Integer.valueOf(o.toString());
			}
		} catch (ClassCastException e) {
			return defaultVal;
		}
	}

	public static int getInt(Map<String, Object> map, String key) {
		return getInt(map, key, 0);
	}

	public static Double getDouble(Map<String, Object> map, String key, double defaultVal) {
		final Object o = map.get(key);
		try {
			if ((o == null || o.equals("")) && defaultVal != 0) {
				return defaultVal;
			} else if ((o == null || o.equals("")) && defaultVal == 0) {
				return 0D;
			} else {
				return Double.valueOf(o.toString());
			}
		} catch (ClassCastException e) {
			return defaultVal;
		}
	}

	public static Double getDouble(Map<String, Object> map, String key) {
		return getDouble(map, key, 0D);
	}

	public static float getFloat(Map<String, Object> map, String key, float defaultVal) {
		final Object o = map.get(key);
		try {
			if (o == null && defaultVal != 0) {
				return defaultVal;
			} else if (o == null && defaultVal == 0) {
				return 0;
			} else {
				return Float.valueOf(o.toString());
			}
		} catch (ClassCastException e) {
			return defaultVal;
		}
	}

	public static float getFloat(Map<String, Object> map, String key) {
		return getFloat(map, key, 0);
	}

	public static BigDecimal getBigDecimal(Map<String, Object> map, String key, double defaultVal) {
		final Object o = map.get(key);
		try {
			if (o == null && defaultVal != 0) {
				return new BigDecimal(defaultVal);
			} else if (o == null && defaultVal == 0) {
				return new BigDecimal(0);
			} else {
				return BigDecimal.valueOf(Double.valueOf(o.toString()));
			}
		} catch (ClassCastException e) {
			return new BigDecimal(defaultVal);
		}
	}

	public static BigDecimal getBigDecimal(Map<String, Object> map, String key) {
		return getBigDecimal(map, key, 0);
	} 
}